<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24" style="margin-top: 3px">
        <div class="head-container">
          <!-- prettier-ignore -->
          <label for="deptName" style="font-size: 13px;">部门名称：</label>
          <el-input
              id="deptName"
              v-model="deptName"
              placeholder="请输入部门名称"
              clearable
              size="small"
              prefix-icon="search"
              style="margin-bottom: 10px; width: 70%"
          />
        </div>
        <div class="head-container">
          <el-tree
              ref="deptTreeRef"
              :data="deptOptions"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              default-expand-all
              @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <transition name="fade">
          <el-form
              :model="queryForm"
              ref="queryFormRef"
              :inline="true"
              label-width="70px"
          >
            <el-form-item label="用户名称" prop="userName">
              <el-input
                  v-model="queryForm.userName"
                  placeholder="请输入用户名称"
                  clearable
                  style="width: 200px"
                  @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="用户昵称" prop="nickName">
              <el-input
                  v-model="queryForm.nickName"
                  placeholder="请输入用户昵称"
                  clearable
                  style="width: 200px"
                  @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input
                  v-model="queryForm.phonenumber"
                  placeholder="请输入手机号码"
                  clearable
                  style="width: 150px"
                  @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="性别" prop="sex">
              <el-select
                  v-model="queryForm.sex"
                  placeholder="请选择性别"
                  style="width: 120px"
                  clearable
                  @change="handleQuery"
              >
                <el-option
                    v-for="dict in sexOptions"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select
                  v-model="queryForm.status"
                  placeholder="请选择状态"
                  style="width: 120px"
                  clearable
                  @change="handleQuery"
              >
                <el-option
                    v-for="dict in statusOptions"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item
                label="创建时间"
                style="font-weight: bold"
            >
              <el-date-picker
                  v-model="dateRange"
                  style="width: 240px"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
            <el-button @click="resetClick">重置</el-button>
            <el-button type="primary" @click="handleQuery">搜索</el-button>
          </el-form>
        </transition>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
                type="primary"
                plain
                icon="plus"
                size="small"
                @click="handleAdd"
            >新增</el-button
            >
          </el-col>
          <el-col :span="1.5" >
            <el-button
                type="success"
                plain
                icon="edit"
                size="small"
                @click="handleUpdate"
            >修改</el-button
            >
          </el-col>
          <el-col :span="1.5" >
            <el-button
                type="danger"
                plain
                icon="delete"
                size="small"
                @click="handleDelete"

            >删除</el-button
            >
          </el-col>
        </el-row>
        <Tbale
            :isSelect="true"
            :table-data="tableData"
            :table-column="tableColumn"
            @pagination-change="getList"
            v-model:page-num="queryForm.pageNum"
            v-model:page-size="queryForm.pageSize"
            :total="total">
          <template #edit="{row}">
            <el-link
                class="table_link_btn"
                :underline="false"
                size="small"
                type="primary"
                :disabled="row.admin"
                @click="handleUpdate(row)">
              <span class="table_link_text">修改</span>
            </el-link>
            <el-link
                class="table_link_btn"
                :underline="false"
                size="small"
                type="primary"
                @click="handleResetPwd(row)"            >
              <span class="table_link_text">重置</span>
            </el-link>
            <el-link
                class="table_link_btn"
                :underline="false"
                :disabled="row.userId === '1'"
                size="small"
                type="danger"
                @click="handleDelete(row)"
            ><span class="table_link_text"
            >删除</span
            ></el-link>
          </template>
        </Tbale>
      </el-col>
    </el-row>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" v-model="open" width="40%" append-to-body >
      <!-- prettier-ignore -->
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickName">
              <el-input
                  v-model="form.nickName"
                  placeholder="请输入用户昵称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属部门" prop="deptId">
              <el-tree-select
                  check-strictly
                  v-model="form.deptId"
                  :data="deptOptions"
                  :props="defaultProps"
                  value-key="id"
                  style="width: 100%;"
                  placeholder="请选择归属部门"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input
                  v-model="form.phonenumber"
                  placeholder="请输入手机号码"
                  maxlength="11"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户邮箱" prop="email">
              <el-input
                  v-model="form.email"
                  placeholder="请输入邮箱"
                  maxlength="50"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
                v-if="form.userId == undefined"
                label="用户名称"
                prop="userName"
            >
              <el-input
                  v-model="form.userName"
                  placeholder="请输入用户名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
                v-if="form.userId == undefined"
                label="用户密码"
                prop="password"
            >
              <el-input
                  v-model="form.password"
                  placeholder="请输入用户密码"
                  type="password"
                  show-password
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户性别">
              <el-select v-model="form.sex" placeholder="请选择性别" style="width: 100%;">
                <el-option
                    v-for="dict in sexOptions"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户状态">
              <el-radio-group v-model="form.status" style="width: 100%;" @change="statusChange">
                <el-radio
                    v-for="dict in statusOptions"
                    :key="dict.label"
                    :label="dict.label"
                    :value="dict.value"
                >{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户岗位">
              <el-select
                  v-model="form.postIds"
                  multiple
                  placeholder="请选择岗位"
                  style="width: 100%;"
              >
                <el-option
                    v-for="item in postOptions"
                    :key="parseInt(item.postId)"
                    :label="item.postName"
                    :value="parseInt(item.postId)"
                    :disabled="item.status == '1'"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属角色">
              <el-select
                  v-model="form.roleIds"
                  multiple
                  placeholder="请选择角色"
                  style="width: 100%;"
              >
                <el-option
                    v-for="item in roleOptions"
                    :key="parseInt(item.roleId)"
                    :label="item.roleName"
                    :value="parseInt(item.roleId)"
                    :disabled="item.status == '1'"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注信息">
              <el-input
                  v-model="form.remark"
                  :autosize="{ minRows: 4, maxRows: 8 }"
                  type="textarea"
                  placeholder="请输入内容"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm"
          >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>
<script setup lang="ts">
import {getCurrentInstance, onMounted, ref, watch} from "vue";
import {addDateRange} from "@/utils/z.ts";
import Tbale from "@/components/Table/ElTable.vue";
import {addUser, delUser, getUser, listUser, resetUserPwd, updateUser} from "@/api/system/user.ts";
import {deptTreeSelect, } from "@/api/system/dept.ts";
import {ElMessage, ElMessageBox} from "element-plus";

const { proxy } = getCurrentInstance() as any;
// 状态数据字典
const statusOptions = ref<any>([
  {
    value: "0",
    label: "正常",
  }, {
    value: "1",
    label: "停用",
  },
]);
const queryForm = ref<any>(
    {
      pageNum: 1,
      pageSize: 10,
      userName: undefined,
      phonenumber: undefined,
      status: undefined,
      deptId: undefined,
      sex: undefined,
    }
)
// 表单校验
const rules = ref<any>({
  userName: [
    {
      required: true,
      message: "用户名称不能为空",
      trigger: "blur",
    },
  ],
  nickName: [
    {
      required: true,
      message: "用户昵称不能为空",
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      message: "用户密码不能为空",
      trigger: "blur",
    },
  ],
  email: [
    {
      type: "email",
      message: "'请输入正确的邮箱地址",
      trigger: ["blur", "change"],
    },
  ],
  phonenumber: [
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
});
const formRef = ref<InstanceType<typeof ElForm>>();
const queryFormRef = ref<InstanceType<typeof ElForm>>();
// 日期范围
const dateRange = ref<any>();
// 表单参数
const form = ref<any>();
// 选中数组
let ids = ref<any>([]);
// 部门名称
const deptName = ref<any>(undefined);
const total = ref(0)
// 弹出层标题
const title = ref<string>("");
// 岗位选项
const postOptions = ref<any>();
// 角色选项
const roleOptions = ref<any>();
// 部门树选项
const deptOptions = ref<any>();
// 是否显示弹出层
const open = ref<boolean>(false);
const tableData = ref<Array<Object>>([])

const tableColumn = ref<Array<Object>>([
  {
    label: '编号',
    prop: 'userId',
  },
  {
    label: '名称',
    prop: 'userName',
  },
  {
    label: '性别',
    prop: 'sex',
  }, {
    label: '昵称',
    prop: 'nickName',
  }, {
    label: '部门',
    prop: 'dept.deptName',
  }, {
    label: '岗位',
    prop: 'postNameArray',
  }, {
    label: '角色',
    prop: 'roleNameArray',
  }, {
    label: '手机号码',
    prop: 'phonenumber',
  },{
    label: '邮箱',
    prop: 'email',
  },{
    label: '状态',
    prop: 'status',
  },{
    label: '创建时间',
    prop: 'createTime',
  }, {
    label: '操作',
    prop: 'edit',
    slot: true,
  },
])
const defaultProps = {
  children: "children",
  label: "label",
};
// 状态数据字典
const sexOptions = ref<any>([
  {
    value: "0",
    label: "男",
  }, {
    value: "1",
    label: "女",
  },{
    value: "2",
    label: "未知",
  },
]);
watch(deptName, (val) => {
  // 根据名称筛选部门树
  proxy.$refs["deptTreeRef"].filter(val);
});
onMounted(() => {
  getTreeselect()
  getList()
})
const handleQuery = () => {
  getList()
}
const getList = () => {
  listUser(addDateRange(queryForm.value, dateRange.value)).then(
      (response: any) => {
        tableData.value = response.rows;
        total.value = parseInt(response.total);
      }
  );
}
/** 查询部门下拉树结构 */
const getTreeselect = () => {
  deptTreeSelect().then((response: any) => {
    deptOptions.value = response.data;
  });
};
// 筛选节点
const filterNode = (value: any, data: any) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};
// 节点单击事件
const handleNodeClick = (data: { id: any }) => {
  queryForm.value.deptId = data.id;
  getList();
};
/** 删除按钮操作 */
const handleDelete = (row: any) => {
  const userIds = row.userId || ids;
  let isAdmin = false;
  if (userIds instanceof Array) {
    userIds.forEach((item) => {
      if (item === "1") {
        isAdmin = true;
        return;
      }
    });
  }

  if (isAdmin) {
    ElMessage({message: "超级管理员不允许删除", type: 'error'})
    return;
  }

  if (userIds === "1") {
    ElMessage({message: "超级管理员不允许删除", type: 'error'})
    return;
  }

  // prettier-ignore
  ElMessageBox.confirm('是否确认删除用户编号为"' + userIds + '"的数据项?', "警告")
      .then(() => {
        return delUser(userIds);
      })
      .then((response: any) => {
        if (response.code === 200) {
          getList();
          ElMessage({message: "删除成功", type: 'success'})
        }
      }).catch(() => {
    console.log("取消了删除");
  });
};
/** 修改按钮操作 */
const handleUpdate = (row: any) => {

  reset();
  getTreeselect();
  const userId = row.userId || ids.value[0];
  getUserBaseInfo("修改用户", userId);
};
// 表单重置
const reset = () => {
  form.value = {
    userId: undefined,
    deptId: undefined,
    userName: undefined,
    nickName: undefined,
    password: undefined,
    phonenumber: undefined,
    email: undefined,
    sex: undefined,
    status: "0",
    remark: undefined,
    postIds: [],
    roleIds: [],
  };
};
const getUserBaseInfo = (dialogTitle: string, userId?: any) => {
  if (userId) {
    getUser(userId).then((response: any) => {
      if (response.code === 200) {
        // const data = response.data;
        const data = response;
        // form.value = response.data.data;
        form.value = response.data;
        postOptions.value = response.posts;
        roleOptions.value = response.roles;
        form.value.postIds = response.postIds;
        form.value.roleIds = response.roleIds;
        /* form.value = {
            userId: formData.userId,
            userName: formData.userName,
            nickName: formData.nickName,
            deptId: formData.deptId,
            phonenumber: formData.phonenumber,
            email: formData.email,
            sex: formData.sex,
            status: formData.status,
            postIds: data.postIds,
            roleIds: data.roleIds,
            password: ""
        } */
        title.value = dialogTitle;
        open.value = true;
      }
    });
  } else {
    getUser(null).then((response: any) => {
      if (response.code === 200) {
        // const data = response.data;
        postOptions.value = response.posts;
        roleOptions.value = response.roles;
        title.value = dialogTitle;
        open.value = true;
      }
    });
  }
};
/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  getTreeselect();

  getUserBaseInfo("添加用户", null);
};
/** 重置按钮操作 */
const resetClick = () => {
  //proxy.resetForm("queryFormRef");
  //proxy.$refs.queryFormRef.resetFields();
  // 表单重置并且移除校验结果(el-form-item必须有prop与表单里文本框v-model对应)
  queryForm.value?.resetFields();
  dateRange.value = "";
  total.value = 0;
  handleQuery();
};
/** 重置密码按钮操作 */
const handleResetPwd =  (row: { userName: string; userId: any }) => {

   ElMessageBox.prompt('请输入"' + row.userName + '"的新密码', "提示")
      .then(({ value }: any)  => {
        resetUserPwd(row.userId, value).then((response: any) => {
          if (response.code === 200) {
            getList();
            ElMessage({message:"修改成功，新密码是：" + value, type: 'success'})
          }
        });
      })
      .catch(() => {
        console.log("密码重置取消");
      });
};
const statusChange = (val: any) => {
  console.log("group选中的值", val);
};
// 取消按钮
const cancel = () => {
  open.value = false;
  reset();
};
/** 提交按钮 */
const submitForm = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (form.value.userId) {
        updateUser(form.value).then((response: any) => {
          if (response.code === 200) {
            ElMessage({message:"修改成功", type: 'success'})
            getList();
            open.value = false;
          }
        });
      } else {
        addUser(form.value).then((response: any) => {
          if (response.code === 200) {
            ElMessage({message:"新增成功", type: 'success'})
          }
        }).finally(() => {
          getList();
          open.value = false;
        });
      }
    }
  });
};
</script>
<style scoped>

</style>
